package com.lyj.thread.reentrantlock;

import java.sql.SQLOutput;
import java.sql.Time;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * 模拟抢票任务：共10张票，3个人抢
 */
public class MyReentrantLockTask extends Thread {
    private Lock lock;
    ReentrantLockDemo demo;

    public MyReentrantLockTask(Lock lock, ReentrantLockDemo demo) {
        this.lock = lock;
        this.demo = demo;
    }

    @Override
    public void run() {
        while (true) {
            try {
                TimeUnit.MILLISECONDS.sleep(200);
                if (!buyTicket())
                    break;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }
    }

    /**
     * 购票
     * @return
     */
    private boolean buyTicket() {
        boolean flag = false;
        try {
            lock.lock();
            // 判断是否还有票
            if (ReentrantLockDemo.tickets > 0) {
                System.out.println(Thread.currentThread().getName() + "，抢到第" + ReentrantLockDemo.tickets + "张票");
                flag = true;
                ReentrantLockDemo.tickets--;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return flag;
    }
}
